package logic.nodes.collision;

import java.util.List;

import logic.nodes.lod.blocks.LeafBlock;
import logic.ships.moveableShip.MovableShip;
import logic.weapons.WeaponFire;
import main.threading.ThreadPoolController;

import com.jme.bounding.BoundingVolume;
import com.jme.math.Vector3f;

public class AntiGravController implements ThreadPoolController {
		
	private MovableShip ship;
	
	public AntiGravController(MovableShip ship) {
		this.ship = ship;
	}
	
	@Override
	public void update(Float time) {		
		if(ship.getParent() == null) return;
		
		for(int i = 0; i < ship.getLeafBlocks().size(); i++) {
			checkLeafBlock(ship.getLeafBlocks().get(i));
		}
	}
	
	protected void checkLeafBlock(LeafBlock leafBlock) {
		BoundingVolume shipBound = ship.getDodgeBound();
		
		if(shipBound == null || leafBlock == null) return;
		
		float shipSize = ship.getSize();
		
		List<CollidableNode> nodes = leafBlock.getLeafNodes();
		for(int i = 0; i < nodes.size(); i++) {
			try {
				CollidableNode node = nodes.get(i);
				if(node == null) continue;
				
				BoundingVolume dodgeBound = node.getDodgeBound();
				if(node instanceof WeaponFire || node == ship || node.getParent() == null 
				|| dodgeBound == null || !dodgeBound.intersects(shipBound)) continue;
				
				float dist = dodgeBound.distanceTo(shipBound.getCenter()) - shipSize - node.getSize();
				if(dist <= 0f) continue;
				
				Vector3f impulseDir = shipBound.getCenter().subtract(dodgeBound.getCenter());
				float impulseSpeed = 2f / dist;
				
				ship.createImpulse(impulseSpeed, impulseDir);
				
				break;
			} catch(IndexOutOfBoundsException e) {}
		}
	}
}